package com.ht.api.call.func.impl.fan;

import java.util.List;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.service.FanService;

import cn.hutool.json.JSONObject;

/**
 * 渠道广告位的编辑前置函数
 */
public class PositionChannelEditBeforeFunctionCall implements IFunctionCall{

	@Override
	public String getName() {
		return "渠道广告位的编辑前置函数";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {

		String newTeamId = param.getStr("team_id");

		Entity position = Db.createSqlParser("position_channel").findById(me.getDataSource(), param.getStr("main_id"));

		String oldTeamId = position.getStr("team_id");

		if (!oldTeamId.equals(newTeamId)) {
			Entity oldFanTeam = Entity.create("fan_team");
			oldFanTeam.setMainId(oldTeamId);
			oldFanTeam.set("relation_cnt", -1);

			Entity newFanTeam = Db.createSqlParser("fan_team").select("main_id,appid").where("main_id",newTeamId).findOne(me.getDataSource());
			newFanTeam.setMainId(newTeamId);
			newFanTeam.set("relation_cnt", 1);

			if (position.getInt("status") == 1) {
				oldFanTeam.set("normal_relation_cnt", -1);
				newFanTeam.set("normal_relation_cnt", 1);

				// 更新配置信息
				List<String> ids = FanService.getRelIds(me.getDataSource(), newTeamId);
				FanService.edit(me.getDataSource(), newFanTeam.getStr("appid"), position.getMainId(), position.getStr("name"), 
						position.getStr("state"), position.getStr("in_type"), ids);
			}

			Db.insert(me.getDataSource(), oldFanTeam);
			Db.insert(me.getDataSource(), newFanTeam);
		}

		return null;
	}
}
